#!/usr/bin/env bash

# ----------------------------------------------------------------------
# Filename:   02-backdoor.sh
# Version:    1.0
# Date:       2024/10/11
# Author:     yaoxiyao
# Email:      yaoxiyao@kylinsec.com.cn
# History：
#             Version 1.0, 2024/10/11
# Function:   隐秘通道
# Out:
#             0 => TPASS
#             1 => TFAIL
#             2 => TCONF
# ----------------------------------------------------------------------
# 任意密码登陆的核心是auth sufficient pam_rootok.so,只要PAM配置文件中包含此配置即可 SSH任意密码登陆
# /etc/pam.d/su与/etc/pam.d/chsh文件中均含有auth sufficient pam_rootok.so，但是用例要求系统不能有隐秘通道
Title_Env_LTFLIB="隐秘通道"

HeadFile_Source_LTFLIB="${LIB_SSHAUTO}"

## TODO : 个性化,初始化
#   Out : 0=>TPASS
#         1=>TFAIL
#         2=>TCONF
TestInit_LTFLIB() {
    testuser="root"
    testip="localhost"
    return $TPASS
}

## TODO : 清理函数
#   Out : 0=>TPASS
#         1=>TFAIL
#         2=>TCONF
TestClean_LTFLIB() {
    # 清理创建的后门
    Debug_LLE "rm -rf ${backdoor_path} ${new_path}"
    rm -rf "${backdoor_path} ${new_path}"
    Debug_LLE "kill $(lsof -t -i :12345)"
    Debug_LLE "kill $(lsof -t -i :23333)"
    kill $(lsof -t -i :12345)
    kill $(lsof -t -i :23333)
    return $TPASS
}

## TODO : 创建后门并远程登录测试
testcase_1() {
    local backdoor_path="/usr/local/su"
    local backdoor_port="12345"
    # 创建后门软链接
    ln -sf /usr/sbin/sshd "${backdoor_path}"
    CommRetParse_LTFLIB "ln -sf /usr/sbin/sshd ${backdoor_path}"

    # 启动带后门的 sshd 监听自定义端口
    "${backdoor_path}" -oport="${backdoor_port}"
    CommRetParse_LTFLIB "${backdoor_path} -oport=${backdoor_port}"

    # 使用 netstat 检查端口是否开启
    netstat -antlp | grep "${backdoor_port}" >/dev/null
    CommRetParse_LTFLIB "netstat -antlp | grep ${backdoor_port} >/dev/null"

    # 远程登录测试
    ssh "${testuser}@${testip}" -p "${backdoor_port}" "ls" >/dev/null
    CommRetParse_LTFLIB "ssh ${testuser}@${testip} -p ${backdoor_port} ls >/dev/null" "False" "yes"
}

## TODO : 更改软链接名称并监听新的端口测试
testcase_2() {
    local new_path="/tmp/chsh"
    local new_port="23333"

    # 更改软链接路径并开启监听新端口
    ln -sf /usr/sbin/sshd "${new_path}"
    CommRetParse_LTFLIB "ln -sf /usr/sbin/sshd ${new_path}"

    "${new_path}" -oport="${new_port}"
    CommRetParse_LTFLIB "${new_path} -oport=${new_port}"

    # 使用新的端口进行远程登录
    ssh "${testuser}@${testip}" -p "${new_port}" "ls" >/dev/null
    CommRetParse_LTFLIB "ssh ${testuser}@${testip} -p ${new_port} ls >/dev/null" "False" "yes"
}

## TODO : 运行测试集
#   Out : 0=>TPASS
#         1=>TFAIL
#         2=>TCONF
Testsuite_LTFLIB() {
    testcase_1
    testcase_2

    return $TPASS
}

#----------------------------------------------#

source "${LIB_LTFLIB}"
Main_LTFLIB $@
